package com.aerozhonghuan.logisticsmall.modules.home.search;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.aerozhonghuan.foundation.base.BaseActivity;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.entity.SearchProductHistory;
import com.aerozhonghuan.logisticsmall.modules.home.logic.HomePageInfoRequest;
import com.aerozhonghuan.logisticsmall.modules.home.search.beans.SearchBean;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by ChenLin on 2019/5/21 18:19.Email&WeChat:7877409@163.com
 */
public class MKeyWordSearchActivity extends BaseActivity implements View.OnClickListener {


    public EditText mSearchText;
    public Button mSearchBtn;
    public DBAdapter mDbAdapter;
    public ArrayList<SearchProductHistory> mSearchProductHistories;
    private Button mBackBtn;
    private Dialog mLoadingDialog;
    private int mScreenHeight;
    private int mSellerId;
    private String mKeyWord;
    private Set<String> mKeys = new HashSet<String>();
    private SoonSearchFragment mSoonSearchFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mkeywork_search_activity);
        initView();
    }

    private void initView() {
        if (mLoadingDialog == null) {
            mLoadingDialog = CommunityTool.getInstance().createLoadingDialog(
                    this, "");
        }
        //获取屏幕高度，减去title高度，减去底部清除button 高度
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenHeight = (int) (dm.heightPixels - CommunityTool.dip2px(this, 150));

        mDbAdapter = new DBAdapter(this);
        mSearchText = (EditText) findViewById(R.id.keyword_title);
        mBackBtn = (Button) findViewById(R.id.back_btn);
        mSearchBtn = (Button) findViewById(R.id.search_btn);
        mBackBtn.setOnClickListener(this);
        mSearchBtn.setOnClickListener(this);

        mSearchProductHistories = mDbAdapter.querySearchProductHistory();
        if (mSearchProductHistories.size() > 0) {
            for (SearchProductHistory productHistory : mSearchProductHistories) {
                mKeys.add(productHistory.getProcutName());
            }
        }
        Intent intent = getIntent();
        mSellerId = intent.getIntExtra("sellerid", 0);

        mSoonSearchFragment = new SoonSearchFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content, mSoonSearchFragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                this.finish();
                break;
            case R.id.search_btn:
                mKeyWord = mSearchText.getText().toString().trim();
                if (TextUtils.isEmpty(mKeyWord)) {
                    Toast.makeText(this, getString(R.string.search_product), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mKeys.add(mKeyWord)) {
                    mDbAdapter.open().insertSearchProductHistory(System.currentTimeMillis(), mKeyWord);
                } else {
                    boolean d = mDbAdapter.open().deleteSearchProductByKeyData(mKeyWord);
                    if (d) {
                        mDbAdapter.open().insertSearchProductHistory(System.currentTimeMillis(), mKeyWord);
                    }
                }
                searchProduct(mKeyWord);
                int listViewHeight = ((int) CommunityTool.dip2px(this, 50)) * mSearchProductHistories.size();
                if (listViewHeight > mScreenHeight) {
                    long firstId = mSearchProductHistories.get(0).getTimeId();
                    long lastId = mSearchProductHistories.get(mSearchProductHistories.size() - 1).getTimeId();
                    if (firstId > lastId) {
                        mDbAdapter.open().deleteSearchProductData(String.valueOf(lastId));
                    } else {
                        mDbAdapter.open().deleteSearchProductData(String.valueOf(firstId));
                    }
                }
                break;
            default:
                break;
        }
    }

    private void searchProduct(String keyword) {
        mLoadingDialog.show();
        try {
            keyword = URLEncoder.encode(keyword, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //请求数据
        HomePageInfoRequest.search(mKeyWord, "100", "1", this, new ProgressDialogIndicator(this), new CommonCallback<SearchBean>() {
            @Override
            public void onSuccess(SearchBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                if (mLoadingDialog.isShowing()) {
                    mLoadingDialog.dismiss();
                }
                ArrayList<GoodsObject> products = messsageBodyObject.datalist;
                Intent intent = new Intent(MKeyWordSearchActivity.this,
                        SearchProductActivity.class);
                intent.putExtra("keyword", mKeyWord);
                intent.putExtra("count_record", messsageBodyObject.total);
                intent.putExtra("search_res", products);
                startActivity(intent);
                finish();
            }
        });
    }
}
